package com.nhc.activity_fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.astrob.NavFrameSDK;
import com.astrob.activitys.DMapActivity;
import com.astrob.model.KeywordHandle;
import com.astrob.model.LonLat;
import com.astrob.model.Msg;
import com.astrob.model.SearchParm;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.astrob.util.Utils;
import com.astrob.view.BaseViewHolder;
import com.nhc.database.dbmodel.WayPoint;
import com.nhc.database.manager.DBDataCenter;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.base.BaseAdapter;
import zuo.biao.library.manager.CityDB;
import zuo.biao.library.model.City;
import zuo.biao.library.model.Entry;
import zuo.biao.library.ui.EditTextInfoActivity;
import zuo.biao.library.ui.EditTextInfoWindow;
import zuo.biao.library.ui.PageScroller;
import zuo.biao.library.ui.PlacePickerWindow;
import zuo.biao.library.ui.TopMenuWindow;
import zuo.biao.library.util.PlaceUtil;
import zuo.biao.library.util.StringUtil;

public class HCSearchActivity extends BaseActivity {
    private final String TAG = "HCSearchActivity";

    //启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    public static final String RESULT_HCSEARCH_TYPEINDEX = "RESULT_HCSEARCH_TYPEINDEX";
    public static final String RESULT_SEARCH_ONLYSELECT = "RESULT_SEARCH_ONLYSELECT";
    public static final String RESULT_SEARCH_ASWARNING = "RESULT_SEARCH_ASWARNING";

    /**
     * 启动这个Activity的Intent
     *
     * @param context
     * @return
     */
    public static Intent createIntent(Context context, int typeIndex, boolean onlyselect) {
        return new Intent(context, HCSearchActivity.class)
                .putExtra(RESULT_SEARCH_ONLYSELECT, onlyselect)
                .putExtra(RESULT_HCSEARCH_TYPEINDEX, typeIndex);
    }

    public static Intent createIntent(Context context, int typeIndex, boolean onlyselect, boolean asWarningpt) {
        return new Intent(context, HCSearchActivity.class)
                .putExtra(RESULT_SEARCH_ONLYSELECT, onlyselect)
                .putExtra(RESULT_HCSEARCH_TYPEINDEX, typeIndex)
                .putExtra(RESULT_SEARCH_ASWARNING, asWarningpt);
    }

    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    int _typeIndex = 0;
    boolean _onlyselect = false;//点选查询结果直接返回，不再onmap
    boolean _asWarningpt = false;//onmap后，添加的航点作为警告点

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hcsearch_activity);

        intent = getIntent();
        _typeIndex = intent.getIntExtra(RESULT_HCSEARCH_TYPEINDEX, _typeIndex);
        _onlyselect = intent.getBooleanExtra(RESULT_SEARCH_ONLYSELECT, _onlyselect);
        _asWarningpt = intent.getBooleanExtra(RESULT_SEARCH_ASWARNING, _asWarningpt);

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>
    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private ListView lv_poilist;

    //示例代码>>>>>>>>
    @Override
    public void initView() {//必须在onCreate方法内调用
        autoSetTitle();//自动设置标题为上个Activity传入的INTENT_TITLE

        //示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        lv_poilist = (ListView) findViewById(R.id.lv_poilist);
        //示例代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    }

    //示例代码<<<<<<<<
    private DemoAdapter adapter;
    //示例代码>>>>>>>>

    /**
     * 示例方法 ：显示列表内容
     *
     * @param list
     */
    private void setList(List<Entry<Integer, String>> list) {
        if (adapter == null) {
            adapter = new DemoAdapter(context);
            lv_poilist.setAdapter(adapter);
        }
        adapter.refresh(list);
    }
    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private List<Entry<Integer, String>> searchpoilist;
    private final int[] SEARCHTYPE_IDS = {
            R.drawable.icon_point, R.drawable.icon_building, R.drawable.icon_government,
            R.drawable.icon_food, R.drawable.icon_hotel, R.drawable.icon_shopping,
            R.drawable.icon_gas, R.drawable.icon_school, R.drawable.icon_hospital,
            R.drawable.icon_traffic, R.drawable.icon_entertainment};

    //All POI Address
    private final String[] SEARCHTYPE_SMFCFG = {
            "", "All POI", "Government",
            "Restaurant", "Hotel", "Shopping",
            "Gasstation", "Education", "Hostial",
            "Traffic", "Entertainments"};

    //示例代码>>>>>>>>>
    @Override
    public void initData() {//必须在onCreate方法内调用
        _centerLL = SysUtils.getInstance().getLL();
        if (DBDataCenter.getInstance().makerEdit != null) {
            _centerLL = DBDataCenter.getInstance().makerEdit.getLL();
        }
        doSearch();
    }

    private boolean mIsSearching = false;
    private String mKey = "";
    private CityDB cityDB;
    private City _selCity;
    public static final String INTENT_PACKAGE_NAME = "INTENT_PACKAGE_NAME";

    private void doSearch() {
        if (mIsSearching) {
            return;
        }

        mIsSearching = true;
        showProgressDialog(R.string.loading);
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                searchpoilist = getList();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        setList(searchpoilist);
                        mIsSearching = false;
                        _isAll = false;
                    }
                });
            }
        });
    }

    private LonLat _centerLL;//城市点距离现在地50km内则使用现在地为查询中心，否则使用选择城市的中心
    private List<NavFrameSDK.POIDescription> mPOIResult = new ArrayList<NavFrameSDK.POIDescription>();//查询结果
    private ArrayList<WayPoint> mWaypointList = new ArrayList<WayPoint>();
    private boolean _isAll = false;

    protected List<Entry<Integer, String>> getList() {
        if (searchpoilist == null) {
            searchpoilist = new ArrayList<Entry<Integer, String>>();
        }
        searchpoilist.clear();

        if (_centerLL == null) {
            return searchpoilist;
        }

        if (_typeIndex < 0 || _typeIndex >= SEARCHTYPE_SMFCFG.length) {
            _typeIndex = 0;
        }

        if (_typeIndex == 0) {
            mWaypointList = DBDataCenter.getInstance().searchWaypt(mKey, _centerLL, _isAll);
            for (int i = 0; i < mWaypointList.size(); i++) {
                searchpoilist.add(new Entry<Integer, String>(i, ""));
            }
        } else {
            LonLat centerLL = Utils.wgs84togcj02(_centerLL.GetLon(), _centerLL.GetLat());
            LonLat carLL = SysUtils.getInstance().getLL();
            carLL = Utils.wgs84togcj02(carLL.GetLon(), carLL.GetLat());
            SearchParm sp = new SearchParm();
            sp.dLon = centerLL.GetLon();
            sp.dLat = centerLL.GetLat();
            sp.dLonCar = carLL.GetLon();
            sp.dLatCar = carLL.GetLat();
            sp.poiType = SEARCHTYPE_SMFCFG[_typeIndex];
            sp.range = 50000;
            sp.keyword = mKey;

            if (sp.keyword.length() < 1) {
                sp.range = 3000;
                if (_typeIndex == 1) {
                    sp.range = 300;
                }
            } else {
                KeywordHandle.getInstance().add(mKey);
                if (_selCity != null) {
//                    return searchPoiBySmartdata();
                }
            }

            Start.getInstance().MapKit().mSearchParm = sp;
            Start.getInstance().MapKit().nearQuery(false);
            mPOIResult = Start.getInstance().MapKit().mPOIResult;
            for (int i = 0; i < mPOIResult.size(); i++) {

                // 这里转为GPS原始坐标；
                LonLat poiLL = Utils.gcj02towgs84(mPOIResult.get(i).position.lon, mPOIResult.get(i).position.lat);
                mPOIResult.get(i).position.lon = poiLL.GetLon();
                mPOIResult.get(i).position.lat = poiLL.GetLat();

                searchpoilist.add(new Entry<Integer, String>(i, ""));
            }
        }

        return searchpoilist;
    }

    protected List<Entry<Integer, String>> searchPoiBySmartdata() {
        if (_selCity == null) {
            return searchpoilist;
        }

        int owner = 0;
        int i = 0;
        NavFrameSDK.AreaDescription area = NavFrameSDK.getInstance().new AreaDescription();
        //0--省+直辖市
        //1--2级+3级
        //2--2级
        //3--3级
        boolean a = Start.getInstance().MapKit().startQueryCity("S", 0, 0);
        while (a) {
            if (!Start.getInstance().MapKit().getResultCity(i, area)) {
                break;
            }
            if (area.name.compareTo(_selCity.getCity()) == 0) {
                owner = area.axid;
                break;
            }
            i++;
        }

        Start.getInstance().MapKit().mSearchParm.keyword = mKey;
        Start.getInstance().MapKit().mSearchParm.owner = owner;
        Start.getInstance().MapKit().mSearchParm.type = 0;
        Start.getInstance().MapKit().mSearchParm.isABC = false;
        NavFrameSDK.CLonLat center = NavFrameSDK.getInstance().new CLonLat();
        center.lon = SysUtils.getInstance().getLL().GetLon();
        center.lat = SysUtils.getInstance().getLL().GetLat();
        Start.getInstance().MapKit().smartQuery(true);

        mPOIResult = Start.getInstance().MapKit().mPOIResult;
        for (i = 0; i < mPOIResult.size(); i++) {

            // 这里转为GPS原始坐标；
            LonLat poiLL = Utils.gcj02towgs84(mPOIResult.get(i).position.lon, mPOIResult.get(i).position.lat);
            mPOIResult.get(i).position.lon = poiLL.GetLon();
            mPOIResult.get(i).position.lat = poiLL.GetLat();

            searchpoilist.add(new Entry<Integer, String>(i, ""));
        }

        return searchpoilist;
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreate方法内调用
        //示例代码<<<<<<<<<<<<<<<<<<<
        lv_poilist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectePOI(position);
            }
        });

        //分页滚动示例代码<<<<<<<<<<<<<<<<<<<
        new PageScroller(lv_poilist).init();
        //分页滚动示例代码>>>>>>>>>>>>>>>>>>>

        //示例代码>>>>>>>>>>>>>>>>>>>
    }

    private void selectePOI(int index) {
        WayPoint wp = null;
        if (_typeIndex == 0) {
            if (index < 0 || index >= mWaypointList.size()) {
                index = 0;
            }
            wp = new WayPoint(mWaypointList.get(index), 0);//需克隆，不能更改航点列表
        } else {
            if (index < 0 || index >= mPOIResult.size()) {
                index = 0;
            }
            wp = new WayPoint(mPOIResult.get(index));
        }

        if (_onlyselect) {
            DBDataCenter.getInstance().makerSeach = wp;
            setResult(Msg.SEACHSELECTEDONE);
            finish();
        } else {
            toActivity(DMapActivity.createIntent(context, wp.getName()
                    , wp.getLL()), REQUEST_TO_ONMAP);
        }
    }

    @Override
    public void onForwardClick(View v) {
        toActivity(TopMenuWindow.createIntent(context, getResources().getStringArray(R.array.top_menu_hcsearch)), REQUEST_TO_TOP_MENU, false);
    }

    //系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //@user 新增方法

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    private final int REQUEST_TO_TOP_MENU = 30;
    private final int REQUEST_TO_EDIT_TEXT_INFO = 23;
    private final int REQUEST_TO_PLACE_PICKER = 10;
    private final int REQUEST_TO_ONMAP = 26;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_TO_ONMAP) {
            return;
        }

        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_TO_EDIT_TEXT_INFO:
                mKey = "";
                if (data != null) {
                    mKey = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                }
                doSearch();
                break;
            case REQUEST_TO_TOP_MENU:
                if (data != null) {
                    switch (data.getIntExtra(TopMenuWindow.RESULT_POSITION, -1)) {
                        case 0:
                            inputKeyword(true);
                            break;
                        case 1:
                            onChangeCity();
                            break;
                        case 2:
                            _isAll = true;
                            doSearch();
                            break;
                        default:
                            break;
                    }
                }
                break;
            case REQUEST_TO_PLACE_PICKER:
                if (data != null) {
                    ArrayList<String> placeList = data.getStringArrayListExtra(PlacePickerWindow.RESULT_PLACE_LIST);
                    if (placeList != null && placeList.size() > PlaceUtil.LEVEL_CITY) {
                        String cityName = StringUtil.getTrimedString(placeList.get(PlaceUtil.LEVEL_CITY));
                        if (cityDB == null) {
                            cityDB = CityDB.getInstance(this, StringUtil.getTrimedString(
                                    getIntent().getStringExtra(INTENT_PACKAGE_NAME)));
                        }
                        tvBaseTitle.setText(cityName);
                        _selCity = cityDB.getCity(cityName);
                        if (_selCity != null) {
                            LonLat cityLL = new LonLat(_selCity.getLongitude(), _selCity.getLatitude());
                            LonLat carLL = SysUtils.getInstance().getLL();
                            double distance = Start.getInstance().MapKit().getDistance(carLL, cityLL);
                            if (distance < 1000) {
                                _centerLL = carLL;
                            } else {
                                _centerLL = cityLL;
                            }
                            mKey = "";
                            doSearch();
                        }
                    }
                }
                break;
        }
    }

    public void onChangeCity() {
        Intent intent = PlacePickerWindow.createIntent(this, this.getPackageName(), 2);
        startActivityForResult(intent, REQUEST_TO_PLACE_PICKER);
    }

    private void inputKeyword(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NICK
                    , getString(R.string.cxgjz), mKey, getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NICK
                    , getString(R.string.cxgjz), mKey);
        }

        toActivity(intent, REQUEST_TO_EDIT_TEXT_INFO, !toWindow);
    }

    //系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Adapter
    public class DemoAdapter extends BaseAdapter<Entry<Integer, String>> {
        public DemoAdapter(Activity context) {
            super(context);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(
                        R.layout.hcpoi_searchresult_view, parent, false);
            }

            ImageView iv_icon = BaseViewHolder.get(convertView, R.id.iv_icon);
            TextView tv_name = BaseViewHolder.get(convertView, R.id.tv_name);
            TextView tv_address = BaseViewHolder.get(convertView, R.id.tv_address);
            TextView tv_distance = BaseViewHolder.get(convertView, R.id.tv_distance);
            TextView tv_dir = BaseViewHolder.get(convertView, R.id.tv_dir);

            final Entry<Integer, String> kvb = getItem(position);
            int index = kvb.getKey();
            LonLat llcar = SysUtils.getInstance().getLL();

            if (_typeIndex == 0) {
                if (index < 0 || index >= mWaypointList.size()) {
                    index = 0;
                }
                WayPoint wp = mWaypointList.get(index);
                iv_icon.setImageResource(wp.getTypeIcon());
                tv_name.setText(wp.getName());
                int distance0 = (int) Start.getInstance().MapKit().getDistance(wp.getLL(), llcar);
                int distance = (int) wp.getDistance();
                if (Math.abs(distance - distance0) > 1000) {
                    //选了城市
//                    tv_distance.setTextColor();
                }
                String SS[] = SysUtils.getInstance().getDistanceStr(distance0);
                tv_distance.setText(SS[0] + " " + SS[1]);
                tv_dir.setText(Start.getInstance().MapKit().getDirection(llcar, wp.getLL()));
                tv_address.setText(SysUtils.getInstance().getTimeStr(wp.getDatetime()));
            } else {
                if (index < 0 || index >= mPOIResult.size()) {
                    index = 0;
                }
                iv_icon.setImageResource(SEARCHTYPE_IDS[_typeIndex]);
                NavFrameSDK.POIDescription data = mPOIResult.get(index);
                tv_name.setText(data.name);
                tv_address.setText(data.address);
                LonLat ll = new LonLat(data.position.lon, data.position.lat);
//                int distance = (int) Start.getInstance().MapKit().getDistance(ll, llcar);
                String SS[] = SysUtils.getInstance().getDistanceStr(data.rank);
                tv_distance.setText(SS[0] + " " + SS[1]);
                tv_dir.setText(Start.getInstance().MapKit().getDirection(llcar, ll));
            }

            return super.getView(position, convertView, parent);
        }

        private final long serialVersionUID = 3L;

        @Override
        public long getItemId(int position) {
//            return getItem(position).getId();
            return serialVersionUID + position;
        }
    }

}